#include "pic_record.h"
#include "ui_pic_record.h"

pic_record::pic_record(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::pic_record)
{
    ui->setupUi(this);
    pixmap=new QPixmap();
    this->picsocket = NULL;
}

pic_record::~pic_record()
{
    delete ui;
}


void pic_record::receive_picture()
{
    char picbuf[1024*1024];
    int length;
    memset(picbuf,0,1024*1024);
    char *len = NULL;
    char commond[50] = {0};
    length = 0;
    int ret =0 ;
    qDebug() << "fun has been called";
    if(this->picsocket == NULL)
    {
       qDebug()<<"picsocket err\n";
       return;
    }
    this->picsocket->waitForReadyRead(30000);

    memset(commond, 0, 50);
    ret = this->picsocket->read(commond, 50);
    if (ret < 1) {
        qDebug() << "recv response failed";
    }
    qDebug() <<"commond is :" <<commond;
    len = strstr(commond, "piclen");
    if (len == NULL) {
        qDebug() << "have no recorad";
        return;
    }

    *len = '\0';
    //从response中读取图片长度
    length = atoi(commond);

    qDebug() << "length: " << length;

    int total = 0;
    //循环读取pic信息
    while (total < length) {
        ret = this->picsocket->read(picbuf+total, length-total);
        if (ret < 0) {
            qDebug() << "recv pic failed" << ret;
            return;
        } else if (ret == 0) {
            this->picsocket->waitForReadyRead(30000);
            continue;
        } else
            total += ret;

        qDebug() << "total: " << total;
    }
    pixmap->loadFromData((const uchar *)picbuf,length, "JPEG");
    ui->label->setPixmap(*pixmap);
}




void pic_record::on_pushButton_3_clicked()
{
    this->picsocket->write("previou picture",50);
    this->receive_picture();
}



void pic_record::on_pushButton_clicked()
{
    this->picsocket->write("next picture",50);
    this->receive_picture();
}
